package com.example.myfoodrecipe.fragments.recipe.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.example.myfoodrecipe.R
import com.example.myfoodrecipe.data.model.Result
import com.example.myfoodrecipe.databinding.FoodItemBinding
import com.example.myfoodrecipe.fragments.recipe.RecipeFragmentDirections

//食物显示页面的recyclerView
class FoodAdapter: RecyclerView.Adapter<FoodAdapter.ItemViewHolder>() {
    //展示的数据
    private var recipeList: List<Result> = emptyList()
    class ItemViewHolder(private val binding: FoodItemBinding): RecyclerView.ViewHolder(binding.root){
        //绑定数据
        fun bind(result: Result){
            binding.result = result
            binding.executePendingBindings()
            //点击一个food进入详情页
            binding.foodContainer.setOnClickListener {
                //传递数据
                val action = RecipeFragmentDirections
                        .actionRecipeFragmentToDetailFragment(result)
                binding.foodContainer.findNavController()
                        .navigate(action)
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
        val adapterLayout = LayoutInflater.from(parent.context)
        return ItemViewHolder(FoodItemBinding.inflate(adapterLayout))
    }

    override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
        holder.bind(recipeList[position])

    }

    override fun getItemCount(): Int {
        return recipeList.size
    }

    fun setData(newData: List<Result>){
        recipeList = newData
        notifyDataSetChanged()
    }
}